package me.jiatao.javestudy.classloader;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by JiaTao on 2018/9/11.
 * Email: 535318720@qq.com
 * Version: 1.0
 * Description:
 */
public class JavaMain {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        ClassLoader loader = new ClassLoader() {
            @Override
            public Class<?> loadClass(String name) throws ClassNotFoundException {
                String fileName = name.substring(name.lastIndexOf(".")+1)+".class";
                InputStream inputStream = getClass().getResourceAsStream(fileName);
                if (inputStream==null)
                    return super.loadClass(name);
                try {
                    byte[] bytes = new byte[inputStream.available()];
                    inputStream.read(bytes);
                    return defineClass(name,bytes,0,bytes.length);

                } catch (IOException e) {
                    e.printStackTrace();
                    throw new ClassNotFoundException(name);
                }
            }

        };
        Object object = loader.loadClass("me.jiatao.javestudy.classloader.JavaMain").newInstance();
        System.out.println(object instanceof JavaMain);

        ClassLoader classLoader = object.getClass().getClassLoader();
        while (classLoader!=null){
            System.out.println(classLoader);
            classLoader = classLoader.getParent();
        }
        if (classLoader==null){
            System.out.println("classLoader == null");
        }

        System.out.println("----------------------------------------");

        Object object2 = new JavaMain();
        ClassLoader classLoader2 = object2.getClass().getClassLoader();

        while (classLoader2!=null){
            System.out.println(classLoader2);
            classLoader2 = classLoader2.getParent();
        }
        if (classLoader2==null){
            System.out.println("classLoader2 == null");
        }

        System.out.println("----------------------------------------");

        Singleton singleton = Singleton.getSingleton();
        System.out.println("counter1="+singleton.counter1);
        System.out.println("counter2="+singleton.counter2);

    }
}
